import { useAtomValue, useSetAtom } from "jotai";
import { allYearsAtom, selectYearAtom } from "@/store/years";
import CaretLeftIcon from "@/assets/icons/caret-left.svg?jsx";
import CaretRightIcon from "@/assets/icons/caret-right.svg?jsx";
import { useCallback, useMemo } from "react";
import event from "@/lib/event";

type TimeControllerProps = {
  queryYear: string;
};
export default function TimeController(props: TimeControllerProps) {
  const { queryYear } = props;
  const setYear = useSetAtom(selectYearAtom);
  const allYears = useAtomValue(allYearsAtom);
  const currentYear = useMemo(() => {
    return allYears.find((_year) => _year.raw === queryYear);
  }, [allYears, queryYear]);
  const currIndex = useMemo(() => {
    return allYears.findIndex((_year) => _year.raw === queryYear);
  }, [allYears, queryYear]);

  const handleNavClick = useCallback(
    (direction: 1 | -1) => {
      const len = allYears.length;
      const newIndex = currIndex + direction;
      const newYear =
        newIndex >= len
          ? allYears[0]
          : newIndex < 0
            ? allYears[len - 1]
            : allYears[newIndex];
      setYear(newYear.raw);

      event.emit("scrollYearIntoView", newYear.raw);
    },
    [currIndex, allYears, setYear],
  );

  return (
    <>
      <div className="flex items-stretch justify-center gap-x-8">
        <button
          className="px-4 text-[#0B9682]"
          onClick={() => handleNavClick(-1)}
        >
          <CaretLeftIcon />
        </button>
        <div className="flex flex-col items-center text-[#09443B]">
          <span className="text-[28px] font-semibold">
            {currentYear?.age || "-"}&nbsp;•&nbsp;{currentYear?.gy_year || "-"}
          </span>
        </div>
        <button
          className="px-4 text-[#0B9682]"
          onClick={() => handleNavClick(1)}
        >
          <CaretRightIcon />
        </button>
      </div>
      <div className="mt-3 text-center text-sm text-[#5D6C6A]">
        <span>{currentYear?.ls_year || "-"}</span>
      </div>
    </>
  );
}
